package com.newlink.building.userinfo.widget

//import com.newlink.building.userinfo.utils.SettingUtil

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.method.ScrollingMovementMethod
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.app.NotificationCompat
import androidx.core.content.FileProvider
import com.newlink.building.common_base.utils.Base_Preference
import com.newlink.building.common_base.utils.ToastUtils
import com.newlink.building.common_base.widget.BaseDialog
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.activity.Module_UserInfo_NotificationActivityNL
import com.newlink.building.userinfo.utils.Module_UserInfo_DownloadUtils
import com.newlink.building.userinfo.utils.Module_UserInfo_EncryptUtils
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File

/**
 * @Author: fvl_dbg
 * @Date: 2022/11/30
 * @Description: app升级使用
 */
class Module_UserInfo_UpdateDialog {

    class Builder(context: Context) : BaseDialog.Builder<Builder>(context), View.OnClickListener {

        private val nameView: TextView? by lazy { findViewById(R.id.tv_update_name) }
        private val detailsView: TextView? by lazy { findViewById(R.id.tv_update_details) }
        private val progressView: ProgressBar? by lazy { findViewById(R.id.pb_update_progress) }
        private val updateView: TextView? by lazy { findViewById(R.id.tv_update_update) }
        private val closeView: TextView? by lazy { findViewById(R.id.tv_update_close) }

        private var apkFile: File? = null

        private var notificationManager: NotificationManager? = null

        private val notificationId = context.applicationInfo.uid

        private var downloadUrl: String? = null

        private var fileMd5: String? = null

        private var forceUpdate = false

        protected var downloadStatus: Boolean by Base_Preference("isDownloading", false)

        private var downloading = downloadStatus

        private var downloadComplete = false

        private var mContext: Context? = null

        private var listener: OnButtonListener? = null

        init {
            setContentView(R.layout.update_dialog)
//            setAnimStyle(AnimAction.ANIM_BOTTOM)
            setCancelable(false)
            setCanceledOnTouchOutside(false)
            updateView?.setOnClickListener(this)
            closeView?.setOnClickListener(this)

            mContext = context
            detailsView?.movementMethod = ScrollingMovementMethod()
        }

        fun setVersionName(name: CharSequence?): Builder = apply {
            nameView?.text = name
        }

        fun setUpdateLog(text: CharSequence?): Builder = apply {
            detailsView?.text = text
            detailsView?.visibility = if (text == null) View.GONE else View.VISIBLE
        }

        fun setForceUpdate(force: Boolean): Builder = apply {
            forceUpdate = force
//            closeView?.visibility = if (force) View.GONE else View.VISIBLE
            if (forceUpdate) {
                closeView?.text = mContext?.getString(R.string.update_never)
            } else {
                closeView?.text = mContext?.getString(R.string.update_no)
            }
            setCancelable(!force)
        }

        fun setButtonListener(listener: OnButtonListener): Builder = apply {
            this.listener = listener
        }

        fun setDownloadUrl(url: String?): Builder = apply {
            downloadUrl = url
        }

        fun setFileMd5(md5: String?): Builder = apply {
            fileMd5 = md5
        }

        override fun onClick(view: View) {
            if (view === closeView) {
                if (listener != null) {
                    listener?.onCloseClick()
                }
                dismiss()
            } else if (view === updateView) {
                if (listener != null) {
                    listener?.onUpdateClick()
                }
                dismiss()
            }
        }

        private fun installDownloadApk() {
//            val apkPath = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)!!.absolutePath
//            val apkName = context.getString(R.string.app_name) + "_v" + nameView?.text.toString() + ".apk"
//            apkFile = File(apkPath, apkName)
            apkFile?.let {
                if (!it.exists()) {
                    return
                }
                val intent = Intent()
                intent.action = Intent.ACTION_VIEW

                val publicUri = FileProvider.getUriForFile(
                    context,
//                    context.getString(R.string.file_provider),
                    "${context.packageName}.fileprovider",
                    apkFile!!
                )

                intent.putExtra(MediaStore.EXTRA_OUTPUT, publicUri)
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                intent.setDataAndType(publicUri, "application/vnd.android.package-archive")

                context.startActivity(intent)
            }
        }

        @OptIn(DelicateCoroutinesApi::class)
        private fun downloadApk() {
            downloadStatus = true
            // 设置对话框不能被取消
            setCancelable(false)
            notificationManager = context.getSystemService(NotificationManager::class.java)

            var channelId = ""
            // 适配 Android 8.0 通知渠道新特性
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel = NotificationChannel(
                    context.getString(R.string.update_notification_channel_id),
                    context.getString(R.string.update_notification_channel_name),
                    NotificationManager.IMPORTANCE_LOW
                )
                channel.enableLights(false)
                channel.enableVibration(false)
                channel.vibrationPattern = longArrayOf(0)
                channel.setSound(null, null)
                notificationManager?.createNotificationChannel(channel)
                channelId = channel.id
            }
            val notificationBuilder: NotificationCompat.Builder =
                NotificationCompat.Builder(context, channelId)
                    // 设置通知时间
                    .setWhen(System.currentTimeMillis())
                    // 设置通知标题
                    .setContentTitle(context.getString(R.string.app_name))
                    // 设置通知小图标
                    .setSmallIcon(R.mipmap.ic_launcher)
                    // 设置通知大图标
                    .setLargeIcon(
                        BitmapFactory.decodeResource(
                            context.getResources(),
                            R.mipmap.ic_launcher
                        )
                    )
                    // 设置通知静音
                    .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
                    // 设置震动频率
                    .setVibrate(longArrayOf(0))
                    // 设置声音文件
                    .setSound(null)
                    // 设置通知的优先级
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)

            // 创建要下载的文件对象
            val intent = Intent(context, Module_UserInfo_NotificationActivityNL::class.java)

            val apkPath =
                context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)!!.absolutePath
            val apkName =
                context.getString(R.string.app_name) + "_v" + nameView?.text.toString() + ".apk"

            // download
            Module_UserInfo_DownloadUtils.get()?.download(
                downloadUrl!!, apkPath, apkName,
                object : Module_UserInfo_DownloadUtils.OnDownloadListener {

                    override fun onDownloadSuccess(file: File?) {
                        Log.e("fvl_dbg", " [UpdateDialog] -> Download = Success :$file")
                        apkFile = File(
                            apkPath,
                            apkName
                        )
                        Log.e("fvl_dbg", "下载文件 MD5 is " + Module_UserInfo_EncryptUtils.getMD5String(apkFile!!))
                        if (apkFile!!.exists() && (Module_UserInfo_EncryptUtils.getMD5String(apkFile!!)
                                .equals(fileMd5))
                        ) {

                            GlobalScope.launch(Dispatchers.Main) {
                                downloadComplete = true
                                notificationBuilder.setContentTitle("下载完成")
                                intent.putExtra(Module_UserInfo_NotificationActivityNL.APP_PATH, apkPath)
                                intent.putExtra(Module_UserInfo_NotificationActivityNL.APP_NAME, apkName)

                                val contentIntent = PendingIntent.getActivity(
                                    context,
                                    0,
                                    intent,
                                    PendingIntent.FLAG_MUTABLE
                                )
                                notificationBuilder.setContentIntent(contentIntent)
                                notificationManager?.notify(
                                    notificationId,
                                    notificationBuilder.build()
                                )
                                installDownloadApk()
                            }
                        } else {
                            Log.e("fvl_dbg", " [UpdateDialog] -> Success :找不到文件")
                        }
                        downloadStatus = false
                    }

                    override fun onDownloading(progress: Int) {
                        notificationBuilder.setContentTitle("下载进行中")
                        notificationBuilder.setContentText("当前下载进度 $progress%")
                        notificationManager?.notify(notificationId, notificationBuilder.build())
                        Log.e("fvl_dbg", " [UpdateDialog] -> Downloading :$progress")
                    }

                    override fun onDownloadFailed(e: Exception?) {
                        notificationBuilder.setContentTitle("下载失败")
                        Log.e("fvl_dbg", " [UpdateDialog] -> Download = Failed :$e")
                        downloadComplete = true
                        downloadStatus = false
                    }
                }
            )

            dismiss()
        }

        override fun show() {

            if (downloadStatus) {
                ToastUtils.showTextToast(context, R.string.update_processing)
                return
            }
            super.show()
        }

        private fun installApk() {
            context.startActivity(getInstallIntent())
        }

        private fun getInstallIntent(): Intent {
            val intent = Intent()
            intent.action = Intent.ACTION_VIEW
            val uri: Uri?
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                val authorityStr = context.packageName + ".provider"
//                val authorityStr1 = BuildConfig.APPLICATION_ID + ".provider"
                uri = FileProvider.getUriForFile(context, authorityStr, apkFile!!)
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            } else {
                uri = Uri.fromFile(apkFile)
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
            intent.setDataAndType(uri, "application/vnd.android.package-archive")
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            return intent
        }
    }


    interface OnButtonListener {
        fun onCloseClick()
        fun onUpdateClick()
    }
}
